#!/usr/bin/env node

/**
 * Simple Performance Benchmark
 *
 * 基础性能测试 - 专为本地MCP工具设计
 */

const { performance } = require('perf_hooks');

class SimpleBenchmark {
    constructor() {
        this.results = [];
    }

    /**
     * Run simple performance benchmarks
     */
    async runBenchmarks() {
        console.log('⚡ Running simple performance benchmarks...\n');

        // Test memory usage
        this.benchmarkMemoryUsage();

        // Test JSON parsing
        this.benchmarkJsonParsing();

        // Test file operations
        await this.benchmarkFileOperations();

        this.printResults();
    }

    /**
     * Benchmark memory usage
     */
    benchmarkMemoryUsage() {
        console.log('📊 Testing memory usage...');

        const startMemory = process.memoryUsage();
        const startTime = performance.now();

        // Simulate some memory operations
        const data = [];
        for (let i = 0; i < 10000; i++) {
            data.push({ id: i, name: `item_${i}`, data: 'x'.repeat(100) });
        }

        const endTime = performance.now();
        const endMemory = process.memoryUsage();

        const duration = endTime - startTime;
        const memoryDiff = endMemory.heapUsed - startMemory.heapUsed;

        this.addResult('Memory Usage', {
            duration: Math.round(duration * 100) / 100,
            memoryUsed: Math.round(memoryDiff / 1024) + 'KB',
            operations: 10000
        });

        console.log(`  ✓ Memory test completed in ${duration.toFixed(2)}ms`);
    }

    /**
     * Benchmark JSON parsing
     */
    benchmarkJsonParsing() {
        console.log('📄 Testing JSON parsing...');

        const testObject = {
            version: '1.0.0',
            providers: { test: { base: 'https://api.test.com', api_key: 'test_key' } },
            settings: { timeout: 30000, retries: 3 }
        };

        const jsonString = JSON.stringify(testObject);
        const iterations = 1000;

        const startTime = performance.now();
        for (let i = 0; i < iterations; i++) {
            JSON.parse(jsonString);
        }
        const endTime = performance.now();

        const duration = endTime - startTime;
        const avgTime = duration / iterations;

        this.addResult('JSON Parsing', {
            totalTime: Math.round(duration * 100) / 100,
            averageTime: Math.round(avgTime * 10000) / 10000,
            operations: iterations
        });

        console.log(`  ✓ JSON parsing completed (${iterations} operations)`);
    }

    /**
     * Benchmark file operations
     */
    async benchmarkFileOperations() {
        console.log('📁 Testing file operations...');

        const fs = require('fs');
        const path = require('path');
        const testFile = path.join(process.cwd(), 'benchmark-test.json');

        const testData = { timestamp: Date.now(), data: 'test'.repeat(1000) };

        // Write test
        const writeStart = performance.now();
        fs.writeFileSync(testFile, JSON.stringify(testData));
        const writeEnd = performance.now();

        // Read test
        const readStart = performance.now();
        const content = fs.readFileSync(testFile, 'utf8');
        JSON.parse(content);
        const readEnd = performance.now();

        // Cleanup
        fs.unlinkSync(testFile);

        const writeTime = writeEnd - writeStart;
        const readTime = readEnd - readStart;

        this.addResult('File Operations', {
            writeTime: Math.round(writeTime * 100) / 100,
            readTime: Math.round(readTime * 100) / 100,
            totalTime: Math.round((writeTime + readTime) * 100) / 100
        });

        console.log(`  ✓ File operations completed`);
    }

    /**
     * Add benchmark result
     */
    addResult(name, data) {
        this.results.push({ name, ...data });
    }

    /**
     * Print benchmark results
     */
    printResults() {
        console.log('\n📈 Benchmark Results:');
        console.log('==================');

        this.results.forEach(result => {
            console.log(`\n${result.name}:`);
            Object.entries(result).forEach(([key, value]) => {
                if (key !== 'name') {
                    console.log(`  ${key}: ${value}`);
                }
            });
        });

        console.log('\n✅ Benchmarks completed successfully!');
    }
}

// Run benchmarks if called directly
if (require.main === module) {
    const benchmark = new SimpleBenchmark();
    benchmark.runBenchmarks().catch(error => {
        console.error('Benchmark failed:', error.message);
        process.exit(1);
    });
}

module.exports = SimpleBenchmark;